<script lang='ts' setup>
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { updateUserPassword } from '~/api/user'

interface RuleForm {
  newPassword: string
}

const ruleFormRef = ref<FormInstance>()
const formSize = ref<ComponentSize>('default')
const ruleForm = reactive<RuleForm>({
  newPassword: '',
})

const router = useRouter()
const userString = localStorage.getItem('userInfo') as string
const user = JSON.parse(userString)

async function submitForm(formEl: FormInstance | undefined) {
  console.log(formEl)
  if (ruleForm.newPassword) {
    await updateUserPassword(user.id, ruleForm.newPassword).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: '修改成功！',
          type: 'success',
        })
        localStorage.clear()
        router.push('/login')
      }
    })
  }else{
    ElMessage({
          message: '请输入密码',
          type: 'error',
        })
  }
}

const rules = reactive<FormRules<RuleForm>>({
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度应为6~12', trigger: 'blur' },
  ],
})
</script>

<template>
  <div class="ml-80 mt-20">
    <el-form
      ref="ruleFormRef"
      style="width: 500px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="密码" prop="newPassword">
        <el-input
          v-model="ruleForm.newPassword" style="width: 240px"
          type="password"
          placeholder="请输入你的新密码"
          show-password
          clearable
        />
      </el-form-item>
    </el-form>

    <!-- <el-input
      v-model="input"
      style="width: 240px"
      type="password"
      placeholder="请输入你的新密码"
      show-password
      clearable
    /> -->
    <el-button type="primary" class="ml-18 mt-3 w-40" @click="submitForm">
      修改
    </el-button>
  </div>
</template>

<style lang='scss' scoped>
</style>

<route lang="yaml">
  meta:
    layout: profile
  </route>
